/**
 * Copyright (C), 2015-2019, bogewang
 * FileName: BaseWebController
 * Author:   foren236598164@aliyun.com
 * Date:     2019/9/19 13:43
 * Description: BaseWebController
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.bogewang.web.base;

import com.alibaba.fastjson.JSONObject;
import com.bogewang.core.base.BaseResponse;
import com.bogewang.core.constants.Constants;
import com.bogewang.web.constants.WebConstants;
import com.bogewang.web.utils.CookieUtils;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.UserAgent;
import nl.bitwalker.useragentutils.Version;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 〈BaseWebController〉
 *
 * @author foren236598164@aliyun.com
 * @create 2019/9/19
 * @since 1.0.0
 */
public class BaseWebController {
    /**
     * 500页面
     */
    protected static final String ERROR_500_FTL = "500.ftl";
    /**
     * 重定向到首页
     */
    private static final String REDIRECT_INDEX = "redirect:/";

    // 接口直接返回true 或者false
    public Boolean isSuccess(BaseResponse<?> baseResp) {
        if (baseResp == null) {
            return false;
        }
        if (baseResp.getRtnCode().equals(Constants.HTTP_RES_CODE_500)) {
            return false;
        }
        return true;
    }

    /**
     * 获取浏览器信息
     *
     * @return
     */
    public String webBrowserInfo(HttpServletRequest request) {
        // 获取浏览器信息
        Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
        // 获取浏览器版本号
        Version version = browser.getVersion(request.getHeader("User-Agent"));
        String info = browser.getName() + "/" + version.getVersion();
        return info;
    }

    public void setErrorMsg(Model model, String errorMsg) {
        model.addAttribute("error", errorMsg);
    }

    public boolean isBlank(CharSequence cs){
        return StringUtils.isBlank(cs);
    }

    protected String redirectIndex(HttpServletRequest request, HttpServletResponse response, BaseResponse<JSONObject> login) {
        JSONObject data = login.getData();
        String token = data.getString("token");
        CookieUtils.setCookie(request, response, WebConstants.LOGIN_TOKEN_COOKIENAME, token);
        return REDIRECT_INDEX;
    }

}